﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using YQBlog.Models;
using YQBlog.General;
using res = Resource.Controllers.Account.Account;
using Common;
using Ninject;
using System.Web.Profile;

namespace YQBlog.Controllers
{

    [WebFilter]
    public class AccountController : Controller
    {
        [Inject]
        public IServices myService { get; set; }

        GeneralConfigInfo configinfo = YQBlog.General.WebUtils.configinfo;
        
        public ActionResult LogOn()
        {
            return View();
        }

        public ActionResult Manage()
        {
            return Redirect("/BlogAdmin/Admin/Index/");
        }

        public ActionResult CheckLogin()
        {
            return View("LogInfo");
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", res.Account_Tip1);
                }
            }
            return View(model);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return  Redirect("/");
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    InitiaAdmin(model.UserName);
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }
            return View(model);
        }

        /// <summary>
        /// 初始化管理员
        /// </summary>
        [NonAction]
        private void InitiaAdmin(string user)
        {
            if (user != "admin")
                return;
            if (Roles.RoleExists("Admin"))
            {
                Roles.AddUserToRole("admin", "Admin");
            }
            else
            {
                Roles.CreateRole("Admin");
                Roles.AddUserToRole("admin", "Admin");
            }
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", res.Account_Tip2);
                }
            }
            return View(model);
        }

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        /// <summary>
        ///  用户信息
        /// </summary>
        public ActionResult UView(string user)
        {
            string Localhost;
            string uid;

            int port = Request.Url.Port;
            string ApplicationPath = Request.ApplicationPath != "/" ? Request.ApplicationPath : string.Empty;
            uid = user;
            Localhost = string.Format("{0}://{1}{2}{3}",
                                 Request.Url.Scheme,
                                 Request.Url.Host,
                                 (port == 80 || port == 0) ? "" : ":" + port,
                                 ApplicationPath);
            ViewBag.Localhost = Localhost;
            ViewBag.uid = uid;
            UserProfileModel userprofile = myService.GetUserProfile(uid);
            ViewBag.GenderInfo = WebUtils.GetGenderList().Find(delegate(SelectItem item) { return item.Value == userprofile.Gender; }).Key; 
            return View(userprofile);
        }

        /// <summary>
        ///  用户中心
        /// </summary>
        [Authorize]
        public ActionResult UCenter()
        {
            string avatarFlashParam;
            string EncodeLocalhost;
            string Localhost;
            string uid;

            int port = Request.Url.Port;
            string ApplicationPath = Request.ApplicationPath != "/" ? Request.ApplicationPath : string.Empty;
            uid = User.Identity.Name;
            Localhost = string.Format("{0}://{1}{2}{3}",
                                 Request.Url.Scheme,
                                 Request.Url.Host,
                                 (port == 80 || port == 0) ? "" : ":" + port,
                                 ApplicationPath);
            EncodeLocalhost = HttpUtility.UrlEncode(Localhost);
            avatarFlashParam = string.Format("{0}/Content/Avatar/common/camera.swf?nt=1&inajax=1&appid=1&input={1}&ucapi={2}/AjaxAvatar.ashx", Localhost, uid, EncodeLocalhost);

            ViewBag.avatarFlashParam = avatarFlashParam;
            ViewBag.Localhost = Localhost;
            ViewBag.uid = uid;
            UserProfileModel userprofile = GetMyProfile();
            ViewBag.GenderInfo = WebUtils.GetGenderList().Find(delegate(SelectItem item) { return item.Value == userprofile.Gender; }).Key; 
            return View(userprofile);
        }

        /// <summary>
        /// 用户Profile
        /// </summary>
        [Authorize]
        public ActionResult MyProfile()
        {
            ViewBag.CI = configinfo;
            ViewData["Gender"] = new SelectList(WebUtils.GetGenderList(), "Value", "Key", GetProfileItem("gender","1"));
            UserProfileModel userprofile = GetMyProfile();
            userprofile.Intro = Utils.RemoveHtml(WebUtils.HtmlToUBB(userprofile.Intro));
            userprofile.Signature = Utils.RemoveHtml(WebUtils.HtmlToUBB(userprofile.Signature));
            return PartialView("_UserProfile", userprofile);
        }

        /// <summary>
        /// 获取当前用户Profile
        /// </summary>
        private UserProfileModel GetMyProfile()
        {
            UserProfileModel userprofile = new UserProfileModel();
            try
            {
                userprofile.NickName = GetProfileItem("nickname");
                userprofile.Signature = GetProfileItem("signature");
                userprofile.Intro = GetProfileItem("intro");
                userprofile.Gender = GetProfileItem("gender", "1");
                userprofile.Birth = GetProfileItem("birth");
                userprofile.Location = GetProfileItem("location");
                userprofile.Website = GetProfileItem("website");
                userprofile.QQ = GetProfileItem("qq");
                userprofile.Sina = GetProfileItem("sina");
                userprofile.Facebook = GetProfileItem("facebook");
                userprofile.Twitter = GetProfileItem("twitter");
                userprofile.Medals = GetProfileItem("medals");
                userprofile.Phone = GetProfileItem("phone");

                string email = GetProfileItem("email");
                if (string.IsNullOrEmpty(email))
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, false /* userIsOnline */);
                    userprofile.Email = currentUser.Email;
                }
                else
                {
                    userprofile.Email = email;
                }
                userprofile.IsSendEmail = GetProfileItem("isSendEmail","1");
            }
            catch
            { }
            return userprofile;
        }

        /// <summary>
        /// 获取当前用户ProfileItem
        /// </summary>
        private string GetProfileItem(string key,string defaultvalue="")
        {
            string value = (String)HttpContext.Profile.GetPropertyValue(key);
            return string.IsNullOrEmpty(value) ? defaultvalue : value;
        }

        /// <summary>
        /// 当前用户Profile更新
        /// </summary>
        [HttpPost]
        [Authorize]
        public ActionResult AjaxUserProfile(UserProfileModel model)
        {
            try
            {
                HttpContext.Profile["nickname"] = Utils.RemoveHtml(WebUtils.MyString(model.NickName));
                HttpContext.Profile["signature"] = WebUtils.ubb2html(WebUtils.MyString(model.Signature));
                HttpContext.Profile["intro"] = WebUtils.ubb2html(WebUtils.MyString(model.Intro));
                HttpContext.Profile["gender"] = model.Gender;
                HttpContext.Profile["birth"] = Utils.RemoveHtml(WebUtils.MyString(model.Birth));
                HttpContext.Profile["location"] = Utils.RemoveHtml(WebUtils.MyString(model.Location));
                HttpContext.Profile["website"] = Utils.RemoveHtml(WebUtils.MyString(model.Website));
                HttpContext.Profile["qq"] = Utils.RemoveHtml(WebUtils.MyString(model.QQ));
                HttpContext.Profile["sina"] = Utils.RemoveHtml(WebUtils.MyString(model.Sina));
                HttpContext.Profile["facebook"] = Utils.RemoveHtml(WebUtils.MyString(model.Facebook));
                HttpContext.Profile["twitter"] = Utils.RemoveHtml(WebUtils.MyString(model.Twitter));
                HttpContext.Profile["medals"] = WebUtils.MyString(model.Medals);
                HttpContext.Profile["phone"] = Utils.RemoveHtml(WebUtils.MyString(model.Phone));
                HttpContext.Profile["email"] = Utils.RemoveHtml(WebUtils.MyString(model.Email));
                HttpContext.Profile["isSendEmail"] = model.IsSendEmail;
                return Content("0", "text/html;charset=UTF-8");
            }
            catch
            {
                return Content("1", "text/html;charset=UTF-8");
            }
        }
        /// <summary>
        ///  用户评论列表(异步)
        /// </summary>
        [Authorize]
        public ActionResult UserCommentList(int p, int size = 20)
        {
            Pager pager = new Pager();
            pager.PageNo = p;
            pager.PageSize = size;
            pager = myService.GetReplyPaging(pager, 1, 0, user: User.Identity.Name);
            ViewBag.PageNo = p;
            ViewBag.PageCount = pager.PageCount;
            AjaxPager ajaxpager = new AjaxPager(3, p, pager.PageCount);
            ViewBag.AjaxPager = ajaxpager.getPageInfoHtml();
            return PartialView("_UserComment", pager.Entity);
        }

        /// <summary>
        ///  用户留言列表(异步)
        /// </summary>
        [Authorize]
        public ActionResult UserNoteList(int p, int size = 20)
        {
            Pager pager = new Pager();
            pager.PageNo = p;
            pager.PageSize = size;
            pager = myService.GetArticlePaging(pager, 6, 0, user: User.Identity.Name);
            ViewBag.PageNo = p;
            ViewBag.PageCount = pager.PageCount;
            AjaxPager ajaxpager = new AjaxPager(3, p, pager.PageCount);
            ViewBag.AjaxPager = ajaxpager.getPageInfoHtml();
            if (pager.Amount > 0)
            {
                blog_varticle varticle = (pager.Entity as IQueryable<blog_varticle>).First();
                CategoryModel category = myService.GetCategoryByID(varticle.cateid);
                ViewBag.NoteUrl = WebUtils.GetCateUrl(category);
            }
            return PartialView("_UserNote", pager.Entity);
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // 请参见 http://go.microsoft.com/fwlink/?LinkID=177550 以查看
            // 状态代码的完整列表。
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return res.Account_Tip3;

                case MembershipCreateStatus.DuplicateEmail:
                    return res.Account_Tip4;

                case MembershipCreateStatus.InvalidPassword:
                    return res.Account_Tip5;

                case MembershipCreateStatus.InvalidEmail:
                    return res.Account_Tip6;

                case MembershipCreateStatus.InvalidAnswer:
                    return res.Account_Tip7;

                case MembershipCreateStatus.InvalidQuestion:
                    return res.Account_Tip8;

                case MembershipCreateStatus.InvalidUserName:
                    return res.Account_Tip9;

                case MembershipCreateStatus.ProviderError:
                    return res.Account_Tip10;

                case MembershipCreateStatus.UserRejected:
                    return res.Account_Tip11;

                default:
                    return res.Account_Tip12;
            }
        }
        #endregion
    }
}
